﻿using log4net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TdxConnector
{
    public class Program
    {
        static BackgroundWorker BackgroundWorker = new BackgroundWorker();
        static ILog log = LogManager.GetLogger("Program");
        static ServiceHost _host;

        static Program()
        {
            BackgroundWorker.DoWork += BackgroundWorker_DoWork;
        }

        static void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Application.Run(new TdxApiDemoForm());
        }

        public static void Run()
        {
            BackgroundWorker.RunWorkerAsync();

            SetupHost();
        }

        private static void SetupHost()
        {
            try
            {
                if (_host != null)
                    _host.Close();
            }
            catch
            {
            }
            try
            {
                log.Info("create host");
                _host = new ServiceHost(typeof(TdxService),
                    new Uri("http://localhost:8733/TdxService")
                    //, new Uri("net.tcp://localhost:8777/TdxService")
                    );

                log.Info("add endpoints");
                _host.AddDefaultEndpoints();
                _host.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetEnabled = true });

                log.Info("open host");
                _host.Open();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);

                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }
    }
}
